import { useEffect, useState } from "react";
import axios from "axios";

const useFetchData = (name) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState();

  useEffect(() => {
    let didCancel = false;
    setError(null);
    if (name) {
      (async () => {
        try {
          setLoading(true);
          const { data } = await axios.get(
            `https://dummyjson.com/${name}?limit=10`
          );
          if (!didCancel) {
            setData(data[name]);
          }
        } catch (error) {
          setError(error);
        } finally {
          setLoading(false);
        }
      })();
    } else {
      setData([]);
      setLoading(false);
    }
    return () => {
      didCancel = true;
    };
  }, [name]);

  return { data, loading, error };
};

export default useFetchData;
